package com.example.miniappssm.service.serviceImpl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.example.miniappssm.service.FileService;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

    @Override
    public String upload(MultipartFile file) {

        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        String accessKeyId = "LTAI5t6QwGiZs2GMSj2hZ62t";
        String accessKeySecret = "pA8OFfvA0d0AxVG1dqZnCMcPSn6yjw";
        String bucketName = "miniapp123";
        try {
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+fileName;
            if (!fileName.contains(".jpg") || !fileName.contains(".png")) {
                fileName += ".jpg";
            }
            ossClient.putObject(bucketName, fileName, inputStream);
            ossClient.shutdown();
            return "https://"+bucketName+"."+endpoint+"/"+fileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public String uploadWithSnapImg(String imgUrl) throws IOException {

        URL urlConnection = new URL(imgUrl);
        HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection.openConnection();
        InputStream in = httpURLConnection.getInputStream();
        byte[] buffer = new byte[1024];
        int len;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((len = in.read(buffer)) != -1){
            out.write(buffer,0,len);
        }
        String url = this.upload(new MockMultipartFile("ezvizimg.png", out.toByteArray()));
        in.close();
        out.close();
        return url;
    }
}
